<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="../../hy/common.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript">
	$(function() {

		//1.初始化Table
		var oTable = new TableInit();
		oTable.Init();
		//2.初始化Button的点击事件
		var oButtonInit = new ButtonInit();
		oButtonInit.Init();
		
	 	$('#addModal').on('hide.bs.modal',function(){
	    	$("#addForm")[0].reset();
	    	$('#addForm').data('bootstrapValidator').resetForm(true);
	    });
	  	$('#edit').on('hide.bs.modal',function(){
	    	$("#editForm")[0].reset();
	    	$('#editForm').data('bootstrapValidator').resetForm(true);
	    }); 
	 	
	 	 //时间控件	
	    $(".form_datetime").datetimepicker({
		 format: "yyyy-mm-dd",
		 autoclose: true,
		 todayBtn: true,
		 todayHighlight: true,
		 showMeridian: true,
		 pickerPosition: "bottom-left",
		 language: 'zh-CN',//中文，需要引用zh-CN.js包
		 startView: 2,//月视图
		 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
		 });
	 	 
	 	 //科目下拉框加载
	    $("#cid").text("");
	    $.ajax({
	        url:'${pageContext.request.contextPath }/books/selectStaff.do',
	        type:"POST",
	        dataType:'json',
	        success:function (result) {
	                $("#sid").append("<option value =''>请选择</option>");
	                $("#sid2").append("<option value =''>请选择</option>");
	            for (var i = 0; i < result.length; i++) {
	                $("#sid").append("<option value="+result[i].staffid+">"+result[i].staffname+"</option>");
	                $("#sid2").append("<option value="+result[i].staffid+">"+result[i].staffname+"</option>");
	            }
	        }
	    });
		 
	});
	
	var TableInit = function () {
	    var oTableInit = new Object();
	    //初始化Table
	    oTableInit.Init = function () {
	        $('#tb_departments').bootstrapTable({
	            url: '${pageContext.request.contextPath }/books/list.do',         //请求后台的URL（*）
	            method: 'get',                      //请求方式（*）
	            toolbar: '#toolbar',                //工具按钮用哪个容器
	            striped: true,                      //是否显示行间隔色
	            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
	            pagination: true,                   //是否显示分页（*）
	            sortable: false,                     //是否启用排序
	            sortOrder: "asc",                   //排序方式
	            queryParams: oTableInit.queryParams,//传递参数（*）
	            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
	            pageNumber:1,                       //初始化加载第一页，默认第一页
	            pageSize: 10,                       //每页的记录行数（*）
	            pageList: [10,20,30],        //可供选择的每页的行数（*）
	            clickToSelect: true,                //是否启用点击选中行
	            height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
	            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
	            detailView: false,                   //是否显示父子表
	            showExport: true,  //是否显示导出按钮  
	            columns: [{
	                checkbox: true
	            }, {
	                field: 'id',
	                title: 'id',
	                visible: false
	            }, {
	                field: 'cname',
	                title: '账套名称'
	            }, {
	                field: 'ename',
	                title: '英文名称'
	            }, {
	                field: 'people',
	                title: '负责人'
	            }]
	        });
	    };

	    //得到查询的参数
	    oTableInit.queryParams = function (params) {
	        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
	        	limit: params.limit,   //页面大小
                page: params.offset/params.limit+1,  //页码
                ename: $("#enamec").val(),
                cname: $("#cnamec").val()
	        };
	        return temp;
	    };
	    return oTableInit;
	};

	var ButtonInit = function () {
	    var oInit = new Object();
	    var postdata = {};

	    oInit.Init = function () {
	        //初始化页面上面的按钮事件
	    };

	    return oInit;
	};

	//查询
	function selectByOther() {
		$('#tb_departments').bootstrapTable('refresh');
	}
	//导出当前页
	function doExport() {
		window.location.href="${pageContext.request.contextPath }/books/export.do?type=1";
	}
	//导出所有
	function exportAll() {
		Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
				function(e) {
					if (!e) {return;}
		window.location.href="${pageContext.request.contextPath }/books/export.do?type=2";
	});
	}
	//删除
	function doDel() {
		var a= $('#tb_departments').bootstrapTable('getSelections');  
        var ids = "";
        for(var i = 0;i<a.length;i++) {
       	 if(i != a.length-1) {
       	 	ids +=a[i].id+",";
       	 }else {
       	 	ids +=a[i].id;
       	 }
        }
		 if(a.length>0) {
			//询问框
			Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
				function(e) {
					if (!e) {return;}
					 $.ajax({
							type: "post",
							url: '${pageContext.request.contextPath }/books/delete.do',
							data: {ids:ids},
							success: function(data){
								if(data >0) {
									toastr.success("删除成功"); 
									setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
										//关闭模态框
										// 父页面刷新
										window.location.reload(); 
									},2000);
								}
							}
						});
				});
		}else {
			toastr.warning('请至少选择一条数据');
		}
	}
	//添加
	function doAdd() {
		$("#addForm")[0].reset();//打开模态框前进行重置
		$("#addModal").modal(open);
	}
	
	//保存
	function save() {
		var bootstrapValidator = $("#addForm").data('bootstrapValidator');  
	    //开启验证
	    bootstrapValidator.validate();  
	    if (bootstrapValidator.isValid()){
	    	$.ajax({
				type : 'post',
				url : '${pageContext.request.contextPath }/books/insert.do',
				data : $("#addForm").serialize(),
				async:false,
				success : function(data) {
					if (data > 0) {
						toastr.success("新增成功"); 
						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload(); 
						},1000);
					} else if (data== -2) {
						toastr.warning("该信息已存在，不能重复添加");
						$('#addModal').modal('hide');
					}else {
						toastr.warning("新增失败"); 
					}
				}
			});
	    }else {
	    	return;
	    }
	}
	
	//去修改
	function doEdit() {
		var a= $('#tb_departments').bootstrapTable('getSelections');  
		 if(a.length==1) {
			$("#edit").modal(open);
			$('#id2').val(a[0].id); 
			$('#sid2').val(a[0].sid);
			$('#cname2').val(a[0].cname);
			$('#ename2').val(a[0].ename);
		}else {
			toastr.warning('请选择一条数据');
		}
	}
	
	//保存修改
	function saveEdit() {
		var bootstrapValidator = $("#editForm").data('bootstrapValidator');  
	    //开启验证
	    bootstrapValidator.validate();  
	    if (bootstrapValidator.isValid()){
	    	$.ajax({
				type : 'post',
				url : '${pageContext.request.contextPath }/books/update.do',
				data : $("#editForm").serialize(),
				async:false,
				success : function(data) {
					if (data > 0) {
						toastr.success("修改成功"); 
						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload(); 
						},1000);
					} else if (data == -2) {
						toastr.warning("该信息已存在，不能重复添加");
						$('#edit').modal('hide');
					}else {
						toastr.warning("修改失败"); 
					}
				}
			});
	    }else {
	    	return;
	    }
	}
	
	//关闭添加表单时清空数据
	function resets() {
		$('#addForm').data('bootstrapValidator').resetForm(true);
	}
	toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上 
</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px">
                        <label class="control-label col-sm-1" for="item">账套名称</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="cnamec">
                        </div>
                        <label class="control-label col-sm-1" for="item">英文名</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="enamec">
                        </div>
                        <div class="col-sm-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary" onclick="selectByOther()">查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>       
		<div id="toolbar" class="btn-group">
			<button id="btn_add" type="button" class="btn btn-default"
				onclick="doAdd()">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
			</button>
			<button id="btn_edit" type="button" class="btn btn-default"
				onclick="doEdit()">
				<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
			</button>
			<button id="btn_delete" onclick="doDel()" type="button"
				class="btn btn-default">
				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
			</button>
			<!-- <button id="btn_export" type="button" class="btn btn-default" onclick="exportAll()">
				<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出所有
			</button> -->
		</div>
		<table id="tb_departments"></table>
	</div>
	<!-- 添加 -->
	<div class="modal fade" id="addModal" tabindex="-1" role="dialog"
		data-backdrop="static" data-keyboard="false"
		aria-labelledby="addModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="addModalLabel">新增账套</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="addForm" method="post">
						
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">账套名称：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input class="form-control" type="text" id="cname" name="cname" >
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">英文名称：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input class="form-control" type="text" id="ename" name="ename">
								<span class="xing"></span>
							</div>
						</div>
						
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">负责人：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<select class="form-control"  id="sid" name="sid"></select>
								<span class="xing"></span>
							</div>
						</div>
						
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal"  onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary" onclick="save()">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	<!-- 修改 -->
	<div class="modal fade" id="edit" tabindex="-1" role="dialog"
		aria-labelledby="updateModalLabel" aria-hidden="true"
		data-backdrop="static" data-keyboard="false">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="updateModalLabel">修改账套</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="editForm" method="post">
						<input type="hidden" id="id2" name="id">
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">账套名称：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input class="form-control" type="text" id="cname2" name="cname" >
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">英文名称：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input class="form-control" type="text" id="ename2" name="ename" >
								<span class="xing"></span>
							</div>
						</div>
						
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">负责人：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<select class="form-control"  id="sid2" name="sid"></select>
								<span class="xing"></span>
							</div>
						</div>
						
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" onclick="resets()">关闭</button>
							<button class="btn btn-primary" onclick="saveEdit()">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	
<script type="text/javascript">
	$(function() {
		var layerTips = parent.layer === undefined ? layui.layer : parent.layer
		$("#addForm").bootstrapValidator({
			feedbackIcons : {
				valid : 'glyphicon glyphicon-ok',
				invalid : 'glyphicon glyphicon-remove',
				validating : 'glyphicon glyphicon-refresh'
			},
			fields : {
				createTime : {
					validators : {
						notEmpty : {
							message : '日期不能为空'
						},
					}
				},
			},
			fields : {
				cid : {
					validators : {
						notEmpty : {
							message : '科目不能为空'
						},
					}
				},
			},
			fields : {
				money : {
					validators : {
						notEmpty : {
							message : '金额不能为空'
						},
					}
				},
			},
		});
		$("#editForm").bootstrapValidator({
			feedbackIcons : {
				valid : 'glyphicon glyphicon-ok',
				invalid : 'glyphicon glyphicon-remove',
				validating : 'glyphicon glyphicon-refresh'
			},
			fields : {
				createTime : {
					validators : {
						notEmpty : {
							message : '日期不能为空'
						},
					}
				},
			},
			fields : {
				cid : {
					validators : {
						notEmpty : {
							message : '科目不能为空'
						},
					}
				},
			},
			fields : {
				money : {
					validators : {
						notEmpty : {
							message : '金额不能为空'
						},
					}
				},
			},
		});
	});
	</script>
</body>
</html>